package com.drakulo.games.ais.ui.component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;

import com.drakulo.games.ais.core.Resource;
import com.drakulo.games.ais.ui.ImageManager;
import com.drakulo.games.ais.ui.UIHelper;
import com.drakulo.games.ais.ui.twlbridge.RootPane;

import de.matthiasmann.twl.Label;

public class ResourceDisplay extends UIComponent {
	/** X coordinate */
	private int x;
	/** Y coordinate */
	private int y;
	/** The resource labels */
	private Map<Resource, Label> labels;
	/** The resource map */
	private Map<Resource, BigDecimal> resourceMap;

	public ResourceDisplay(RootPane twlRootPane, int x, int y) {
		this.labels = new HashMap<Resource, Label>();
		this.x = x;
		this.y = y;
		int dx = x + 5 + 3 + 24;
		int dy = y + 5 + 3;
		for (Resource r : Resource.values()) {
			Label l = new Label();
			l.setTheme("resourceLabel");
			l.setSize(80, 15);
			l.setPosition(dx, dy);
			l.setText("0");
			twlRootPane.add(l);
			this.labels.put(r, l);
			dy += 23;
		}

		setWidth(125);
		setHeight(106);
		resourceMap = new HashMap<Resource, BigDecimal>();
	}

	@Override
	public void render(Graphics g) throws SlickException {
		if(!isShown()){
			return;
		}
		final int padd = 5;
		UIHelper.drawWindow(g, x, y, getWidth(), getHeight(), padd);

		Resource[] resources = Resource.values();
		Image img;
		int dy = y + padd + 3;
		int dx = x + padd + 3;
		Label lbl;
		for (Resource r : resources) {
			UIHelper.drawDarkBox(g, dx, dy, 24, 20);
			img = ImageManager.getGfx(r.getGfxBase() + "-small");
			img.draw(dx + 3, dy, r.getColor());

			lbl = labels.get(r);
			UIHelper.drawDarkBox(g, dx + 24, dy, lbl.getWidth() + 4, 15);

			dy += 23;
		}
	}

	@Override
	public void update(Input input) throws SlickException {
		Resource[] resources = Resource.values();
		for (Resource r : resources) {
			BigDecimal v = resourceMap.get(r);
			String value;
			if (v == null) {
				value = "0";
			} else {
				value = resourceMap.get(r).toString();
			}
			Label lbl = this.labels.get(r);
			lbl.setText(value);
		}
	}

	public void setMap(Map<Resource, BigDecimal> map) {
		resourceMap = map;
	}

	public void show() {
		super.show();
		display(true);
	}

	public void hide() {
		super.hide();
		display(false);
	}

	private void display(boolean show) {
		for (Resource r : labels.keySet()) {
			labels.get(r).setVisible(show);
		}
	}
}
